package com.example.eci_quartz.cloudcc.impl;

import com.example.eci_quartz.cloudcc.commcon.CommonMethod;
import com.example.eci_quartz.cloudcc.commcon.DataGroupUtil;
import com.example.eci_quartz.cloudcc.dao.DefaultConnectionFactory;
import com.example.eci_quartz.cloudcc.dao.baseDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 *零件库存
 */
public class PeijianOrderImpl extends baseDao {

	SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
	SimpleDateFormat sdfY= new SimpleDateFormat("yyyy");
	SimpleDateFormat sdfM= new SimpleDateFormat("MMdd");
	static String binding = InsertXMInfo();
	/**
	 * T+1获取DBS系统中的零件库存
	 * @throws SQLException
	 * @throws ParseException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static String PeijianOrder(){
		Connection conn =null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		List<Map> updatelist =null;
		List<Map> insertlist =null;
		SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy");
		Calendar cal1=Calendar.getInstance();
	    cal1.set(Calendar.DATE,cal1.get(Calendar.DATE)-1);
	    String firstDay1=format.format(cal1.getTime());

	    Calendar cal2=Calendar.getInstance();
	    cal2.set(Calendar.DATE,cal2.get(Calendar.DATE)-2);
	    String firstDay2=format.format(cal2.getTime());
	    Calendar cal3=Calendar.getInstance();
	    cal3.set(Calendar.DATE,cal3.get(Calendar.DATE)-3);
	    String firstDay3=format.format(cal3.getTime());

	    Calendar cal4=Calendar.getInstance();
	    cal4.set(Calendar.DATE,cal4.get(Calendar.DATE)-4);
	    String firstDay4=format.format(cal4.getTime());
          //获取系统当天时间
        String newDate=format.format(new Date());
        String queryDay="'"+newDate+"','"+firstDay1+"','"+firstDay2+"','"+firstDay3+"','"+firstDay4+"'";


		String info = "false";

		String orderinfo = "";//查询返回来的值
		String order_datas = "";//查询成功返回来的数据
		Map<String, Map> orderMap = null;
		Map<String, Map>  fgsMap=null;

		//118196- 数据量太大，分批次更新数据到系统
		String sql="select *  FROM LIBJ49FSMS.STOCK "
		+" WHERE  DATE1 in("+queryDay+") OR DATE2 in("+queryDay+") OR DATE3 in("+queryDay+")";
		int count=1;
		try {
			fgsMap=getfgsMap();//获取分公司信息
			orderMap = new HashMap<String, Map>();// map<销售订单编号，销售订单对象值>

			conn = new DefaultConnectionFactory().getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			Map<String,Map> rsMap=new HashMap<String,Map>();//map<零件号，零件数据>从DBS查询出来的
			String PANO20S="";//零件号数组
			if (rs != null) {
				while (rs.next()) {
					Map mapObj=new HashMap();
					//零件号
					String PANO20=(rs.getString("PANO20") == null ? "" : rs.getString("PANO20")+ "").trim();
          			//分公司 +仓库
					String ckh =(rs.getString("STNO") == null ? "" : rs.getString("STNO")+ "").trim();
					//分公司
					if(ckh.equals("00")){ //00:死库存
						mapObj.put("fgs",null);
					}else{
						mapObj.put("fgs",(fgsMap.get(ckh)==null?"":fgsMap.get(ckh)+"").trim());	//分公司
					}
					mapObj.put("sfjktb", 1);
					//仓库号
					mapObj.put("ckh",ckh);
					// 货源地
					String sos=(rs.getString("SOS1") == null ? "" : rs.getString("SOS1")+ "").trim();
					mapObj.put("sos",sos);
					// 库位号
					mapObj.put("kwh",(rs.getString("BINLOC") == null ? "" : rs.getString("BINLOC")+ "").trim());
					// 零件名称
					mapObj.put("ljmc",(rs.getString("DS18") == null ? "" : rs.getString("DS18")+ "").trim());
					// 现货数量--
					mapObj.put("xhsl",(rs.getString("QYHND") == null ? "" : rs.getString("QYHND")+ "").trim());
					// 补库数量--订货数量
					mapObj.put("bksl",(rs.getString("QYOR") == null ? "" : rs.getString("QYOR")+ "").trim());
					// 重量
					mapObj.put("zl",(rs.getString("GRSSWT") == null ? "" : rs.getString("GRSSWT")+ "").trim());
					// 零件类型代码
					mapObj.put("divi",(rs.getString("CMCD") == null ? "" : rs.getString("CMCD")+ "").trim());
					// 零件类型
					mapObj.put("ljlx",(rs.getString("BECTYC") == null ? "" : rs.getString("BECTYC")+ "").trim());
					String tbId="";
					if(PANO20!=null && !"".equals(PANO20)){
						tbId=PANO20+"-"+ckh+"-"+sos;
						PANO20S+="'"+tbId+"',";
						mapObj.put("tbId", tbId);
						mapObj.put("name", PANO20);
						rsMap.put(tbId, mapObj);

					}
			}

			 String result="";
			 //判断零件号是否存在
		     if(PANO20S!=null&&!"".equals(PANO20S)){
					//查询系统中全部的零件库存
					String data_query = "serviceName=cqlQuery&objectApiName=ljkc" +
							"&expressions=select l.id,l.tbId from ljkc l " +
							"where l.tbId is not null and l.tbId in ("+PANO20S.substring(0, PANO20S.length()-1)+")  " +
									"and l.is_deleted='0'&binding=";//查询零件库存信息  直接查询零件库存全量
					orderinfo = operate(data_query+ binding);
					//判断binding是否失效，如果失效，就重新获取
					JSONObject fromObject =null;
					if(CommonMethod.isJSONValid(orderinfo)){
						fromObject = JSONObject.fromObject(orderinfo);
						result= fromObject.getString("result")==null?"":fromObject.getString("result");
					}
					if(!"true".equals(result)){

						binding = InsertXMInfo();

						orderinfo=operate(data_query+binding);
						fromObject = JSONObject.fromObject(orderinfo);
						if(CommonMethod.isJSONValid(orderinfo)){
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
					}
					result = fromObject.getString("result")==null?"":fromObject.getString("result");
					String returninfo = "[" + orderinfo + "]";// 手动转换成json格式，方便取值
					if (!"[]".equals(returninfo)&&orderinfo!=null) {
						JSONArray brand_list = JSONArray.fromObject(returninfo);
						if (brand_list != null) {
							for (int j = 0; j < brand_list.size(); j++) {
								JSONObject brandInfo = (JSONObject) brand_list.get(j);
								String Result = brandInfo.get("result") == null ? ""
										: brandInfo.get("result") + "";// 获取返回值
								String date = brandInfo.get("data") == null ? ""
										: brandInfo.get("data") + "";// 获取返回值
								if ("true".equals(Result)) {
									order_datas = date;
								}
							}
						}
					}
					// 查询CRM系统中零件库存的信息并存入到map中
					if (order_datas != "[]"&&!"".equals(order_datas)) {
						JSONArray datas_list = JSONArray.fromObject(order_datas);
						if (datas_list != null) {
							for (int i = 0; i < datas_list.size(); i++) {
								JSONObject accObj = (JSONObject) datas_list.get(i);
								JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
								//DBS系统中的零件号
							    String ljh= (accObj.get("tbId")==null? "" : accObj.get("tbId").toString()).trim();
							    if(ljh!=null&&!"".equals(ljh)){
							    	order_newObj.put("id", accObj.get("id"));
									order_newObj.put("ljh", ljh);
									orderMap.put(ljh,order_newObj);
							    }
							}
						}
					}
			  }

			JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
			order_newObj.put("result",result);
			orderMap.put("result",order_newObj);
			//判断零件是新增还是更新
			if(rsMap.size()>0&&rsMap!=null){
			    updatelist = new ArrayList<Map>();
				insertlist = new ArrayList<Map>();
			   for(String lj_ck:rsMap.keySet()){
				    Map ljObj=rsMap.get(lj_ck);//获取DBS中的客户数据
				   if(orderMap!=null&&orderMap.get("result").containsValue("true")){
					   if (orderMap.size()>1&&orderMap.containsKey(lj_ck)) {// 更新零件信息
						   Map ljMap =orderMap.get(lj_ck);
						   ljObj.put("id",ljMap.get("id"));
							updatelist.add(ljObj);
						} else {// 新建零件库存订单
							insertlist.add(ljObj);
						 }
					 }
				}
			}
			//插入新的零件库存
			if (insertlist!=null&&insertlist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataOneGroup(insertlist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayInsert = JSONArray.fromObject(amList);
						String jsonstr=jsonArrayInsert.toString();
						jsonstr = java.net.URLEncoder.encode(jsonstr, "UTF-8");
						String data_insert = "serviceName=insert&objectApiName=ljkc&data="+jsonstr+"&binding=";//insertLt批量插入，不走触发器
			            String insertinfo=operate(data_insert+binding);//用http方式调用insert方法，插入故障代码信息

						//判断binding是否失效，如果失效，就重新获取
			    		JSONObject fromObject =null;
						if(CommonMethod.isJSONValid(orderinfo)){
							fromObject = JSONObject.fromObject(orderinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding = InsertXMInfo();
							insertinfo=operate(data_insert+binding);
						}
					    info="insert_success";
					}
				}
			}
			//更新系统中的零件库存
			if (updatelist!=null&&updatelist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(updatelist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayUpdate = JSONArray.fromObject(amList);
						String jsonstr_update=jsonArrayUpdate.toString();
						jsonstr_update = java.net.URLEncoder.encode(jsonstr_update, "UTF-8");
						String data_update = "serviceName=updateLt&objectApiName=ljkc&data="+jsonstr_update+"&binding=";//updateLt批量更新，不走触发器
			            String updateInfo=operate(data_update+binding);//用http方式调用update方法，插入故障代码信息

						//判断binding是否失效，如果失效，就重新获取
			        	JSONObject fromObject =null;
						if(CommonMethod.isJSONValid(orderinfo)){
							fromObject = JSONObject.fromObject(orderinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding = InsertXMInfo();
							updateInfo=operate(data_update+binding);
						}
			            info="update_success";
					}
				}
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return info;
	}

	/**
	  *查询分公司 fgs
	  * */
	@SuppressWarnings("rawtypes")
	public static Map getfgsMap(){
		String data_query = "serviceName=cqlQuery&objectApiName=fgs" +
				"&expressions=select id,StoreNo from fgs " +
				"where StoreNo is not null and is_deleted='0'&binding=";//查询客户信息
		String khinfo = "";//查询返回来的值
		String kh_datas = "";//查询成功返回来的数据
		Map<String, String> ckMap = null;
		try {
			ckMap = new HashMap<String, String>();// map<客户编号，客户对象值>
			khinfo = operate(data_query+binding);//通过http方式调用咱们平台的查询方法
			//判断binding是否失效，如果失效，就重新获取
			JSONObject fromObject =null;
			String result="";
			if(CommonMethod.isJSONValid(khinfo)){
				fromObject = JSONObject.fromObject(khinfo);
				result= fromObject.getString("result")==null?"":fromObject.getString("result");
			}
			if(!"true".equals(result)){
				binding = InsertXMInfo();
				khinfo=operate(data_query+binding);
			}

			String returninfo = "[" + khinfo + "]";// 手动转换成json格式，方便取值
			if (returninfo != "[]"&&khinfo!=null) {
				JSONArray brand_list = JSONArray.fromObject(returninfo);
				if (brand_list != null) {
					for (int j = 0; j < brand_list.size(); j++) {
						JSONObject brandInfo = (JSONObject) brand_list.get(j);
						String Result = brandInfo.get("result") == null ? ""
								: brandInfo.get("result") + "";// 获取返回值
						String date = brandInfo.get("data") == null ? ""
								: brandInfo.get("data") + "";// 获取查询结果的返回值
						if ("true".equals(Result)) {
							kh_datas = date;
						}
					}
				}
			}
			// 查询crm系统中客户的信息并存入到map中
			if (kh_datas != "[]"&&!"".equals(kh_datas)) {
				JSONArray datas_list = JSONArray.fromObject(kh_datas);
				if (datas_list != null) {
					for (int i = 0; i < datas_list.size(); i++) {
						JSONObject accObj = (JSONObject) datas_list.get(i);
						String StoreNo= (accObj.get("StoreNo")==null?"":accObj.get("StoreNo")+"").trim();
						if(StoreNo!=null&&!"".equals(StoreNo)){
							ckMap.put(accObj.get("StoreNo").toString(), accObj.get("id").toString());
						}
					}
				}
			}
		}catch (Exception e) {
			System.out.println("erro2:"+e);
		}
		return ckMap;
	}


	@SuppressWarnings("null")
	public  void getNmber() {
		String sql="select *  FROM LIBJ49FSMS.STOCK";
		Connection conn =null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			int count=1;
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next()){
            }
		} catch (SQLException e) {
			System.out.println("erro3:"+e);
			e.printStackTrace();
		}
	}


}
